﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Foggy.Settings
{
    using Foggy.Data;
    using Foggy.Data.Settings;

    public class SettingsService : ISettingsService
    {
        public T GetSettingOrDefault<T>(Setting setting, T defaultValue)
        {
            var settingName = setting.ToString();

            SettingDto currentSetting;

            using (var context = new FoggyContext())
            {
                currentSetting = context.Settings.FirstOrDefault(s => s.Name == settingName);               
            }

            if (currentSetting != null)
            {
                return (T)Convert.ChangeType(currentSetting.Value, typeof(T));
            }

            return defaultValue;
        }

        public void SetSetting<T>(Setting setting, T value)
        {
            var settingName = setting.ToString();

            using (var context = new FoggyContext())
            {
                var currentSetting = context.Settings.FirstOrDefault(s => s.Name == settingName);

                if (currentSetting == null)
                {
                    var newSetting = new SettingDto { Name = settingName, Value = value.ToString() };
                    context.Settings.Add(newSetting);
                }
                else
                {
                    currentSetting.Value = value.ToString();
                }

                context.SaveChanges();
            }
        }
    }
}